const express = require('express'),
    route = express.Router(),
    { writeFile } = require('../utils/promiseFS'),
    CANDIDATE_PATH = './json/candidates.json';

route.get('/info', (req, res) => {
    const personID = req.session.personID;
    if (personID) {
        //=>The client will pass in a candidate ID. We find the same information as the ID in all candidates and return
        let { candidateID } = req.query;
        candidateID = parseFloat(candidateID);
        console.log(req.query, req.candidateDATA)
        let item = req.candidateDATA.find(item => {
            return parseFloat(item.id) === candidateID;
        });
        if (item) {
            res.send({
                code: 0,
                msg: 'OK!',
                data: item
            });
            return;
        }
        res.send({
            code: 1,
            msg: 'NO!',
            data: null
        });
        return;
    }
    res.send({
        code: 1,
        msg: 'NO!',
        data: null
    });
});

route.get('/list', (req, res) => {
    const personID = req.session.personID;
    console.log(req.session)
    if (personID) {
        res.send({
            code: 0,
            msg: 'OK!',
            data: req.candidateDATA
        });
        return;
    }
    res.send({ code: 1, msg: 'NO!', data: null });
});

route.post('/create', (req, res) => {
    candidateInfo = {
        id: Date.now(),
        created_at: Date.now(),
        ...req.body
    };

    req.candidateDATA.push(candidateInfo);

    writeFile(CANDIDATE_PATH, req.candidateDATA).then(() => {
        res.send({ code: 0, msg: 'OK!', data: candidateInfo });
    }).catch(() => {
        res.send({ code: 1, msg: 'NO!' });
    });
});

module.exports = route;